//
//  RoundedSegmentedControl.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/19/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit

// MARK - UI View, with padding for segmented control
final class RoundedSCView: UIView {
    public var transportSelect: RoundedSegmentedControl!
    public var currentValue: String {
        get {
            return items[transportSelect.selectedSegmentIndex] as! String
        }
    }
    private var items: [Any]!
    
    func updateItems (items: [Any], padding: CGSize?=CGSize(width: 16, height: 12)) {
        self.items = items
        transportSelect = RoundedSegmentedControl(items: items)
        transportSelect.selectedSegmentIndex = 0

        let itemFont = UIFont.systemFont(ofSize: 15.0, weight: .medium)
        
        let selectedTitle = [NSAttributedString.Key.foregroundColor: UIColor.blueColor,
                             NSAttributedString.Key.font: itemFont]
        transportSelect.setTitleTextAttributes(selectedTitle, for: .selected)
        
        
        let normalTitle = [NSAttributedString.Key.foregroundColor: UIColor.white,
                           NSAttributedString.Key.font: itemFont]
        
        transportSelect.setTitleTextAttributes(normalTitle, for: .normal)
        self.addSubview(transportSelect)
        transportSelect.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-1 * padding!.width)
            make.height.equalToSuperview().offset(-1 * padding!.height)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
    }
    
    
    init () {
        super.init(frame: .zero)
        self.backgroundColor = .blueColor
        self.layer.cornerRadius = 10
        self.clipsToBounds = true
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - Segmented Control, where every segment has corner radius
final class RoundedSegmentedControl: UISegmentedControl {
    override func layoutSubviews() {
        super.layoutSubviews()
        if #available(iOS 13.0, *) {
            selectedSegmentTintColor = .clear
        } else {
            tintColor = .clear
        }
        for (index, subview) in subviews.enumerated() {
            if ((subviews[index] as? UIImageView) != nil) && index == selectedSegmentIndex {
                subview.backgroundColor = .white
                subview.clipsToBounds = true
                subview.layer.cornerRadius = 10
            } else {
                subview.backgroundColor = .clear
            }
        }
    }
}

